# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'P88882018071010000037': {  # witch
        'API_KEY': '1c6482b9a3d948fc97c354f90541824b',
        'gateway': 'http://gateway.zfpfpay.com/simple-web-gateway/scan/apply',
        'query_gateway': 'http://gateway.zfpfpay.com/simple-web-gateway/trade/singleQuery?merchantNo={}&outTradeNo={}&sign={}',
    },
    'P88882018071810000059': {  # witch 支付宝 1到10000任意金额整数
        'API_KEY': '90b282f2585648908338bda3e3b48e4a',
        'gateway': 'http://gateway.zfpfpay.com/simple-web-gateway/scan/apply',
        'query_gateway': 'http://gateway.zfpfpay.com/simple-web-gateway/trade/singleQuery?merchantNo={}&outTradeNo={}&sign={}',
    },
    'P88882018082810000160': {  # loki 支付宝3%（1---5000之间的整数）D0结算
        'API_KEY': '50f9556addc045db81b9e69f9847c11a',
        'gateway': 'http://gateway.zfpfpay.com/simple-web-gateway/scan/apply',
        'query_gateway': 'http://gateway.zfpfpay.com/simple-web-gateway/trade/singleQuery?merchantNo={}&outTradeNo={}&sign={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'secretKey=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("zfpfpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'wx_pay_wap_d0'
    elif service == 'alipay':
        payType = 'ali_pay_wap_t0'
    elif service == 'quick':
        payType = 'kj_pay_d0'
    else:
        payType = 'kj_pay_d0'
    return payType


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantNo', app_id),
        ('orderPrice', '%.2f' % pay_amount),
        ('outOrderNo', str(pay.id)),
        ('tradeType', _get_pay_type(service)),
        ('tradeTime', local_now().strftime('%Y%m%d%H%M%S')),
        ('goodsName', 'charge'),
        ('tradeIp', _get_device_ip(info)),
        ('returnUrl', '{}/pay/api/{}/zfpfpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('notifyUrl', '{}/pay/api/{}/zfpfpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("zfpfpay create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("zfpfpay data rsp : %s, oid: %s", response.text, str(pay.id))
    return {'charge_info': json.loads(response.text)['payMsg']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("zfpfpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['outOrderNo']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('zfpfpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['tradeStatus'])
    trade_no = data['tradeNo']
    total_fee = float(data['orderPrice'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 1:成功 ，0:失败
    if trade_status in ['SUCCESS', 'FINISH']:
        _LOGGER.info('zfpfpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantNo', app_id),
        ('outTradeNo', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    url = _get_query_gateway(app_id).format(parameter_dict['merchantNo'], parameter_dict['outTradeNo'],
                                            parameter_dict['sign'])
    _LOGGER.info('zfpfpay query url, %s', url)
    response = requests.get(url)
    _LOGGER.info('zfpfpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['orderStatus'])
        total_fee = float(data['orderPrice'])
        trade_no = data['tradeNo']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # SUCCESS 交易成功（支付成功后状态）
        # FINISH 交易完成（对完帐以后状态）
        # FAILED 交易失败
        # WAITING_PAYMENT 等待支付
        if trade_status in ['SUCCESS', 'FINISH']:
            _LOGGER.info('zfpfpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
